<template>
  <CommonDialog :title="typeId?'编辑':'新增'+'分类'" @handleCancel="cancel" v-model="visible" :confirmLoading="loading">
    <Form ref="formEl" :model="formData" :rules="rules" label-position="top">
      <FormItem label="分类名称" prop="name">
        <Input
          v-model="formData.name"
          maxlength="20"
          show-word-limit
          placeholder="请输入分类名称"
          clearable
        ></Input>
      </FormItem>
      <FormItem label="分类描述" prop="description">
        <Input
          v-model="formData.description"
          maxlength="500"
          show-word-limit
          type="textarea"
          :rows="4"
          placeholder="请输入分类描述"
        />
      </FormItem>
    </Form>
    <template #footer>
      <Button @click="cancel">取消</Button>
      <Button type="primary" @click="submit">确认</Button>
    </template>
  </CommonDialog>
</template>

<script setup>
import { ref } from 'vue';
import { Message } from 'view-ui-plus';
import { createAgentType, updateAgentType } from '@/api/modules/agent';
import CommonDialog from '@/components/CommonDialog/index.vue';

const emit = defineEmits(['cancel', 'submit']);
// 弹窗显示
const visible = ref(false);
const loading = ref(false)


// 智能体表单
const formEl = ref(null)
const formData = ref({
  name: '',
  description: '',
});
const rules = ref({
  name: [{ required: true, message: '请填写分类名称', trigger: 'blur' }],
})

const typeId = ref(undefined);

// 初始化弹窗
const init = (item) => {
  visible.value = true;
  formEl.value.resetFields();
  if (item) {
    typeId.value = item.id;
    formData.value.name = item.name;
    formData.value.description = item.description;
  }
};

/**
* 提交表单
*/
const submit = async () => {
  let valid = await formEl.value.validate((valid, fild) => valid ? valid : fild);
  if (!valid) return;
  loading.value = true;
  try {
    await (typeId.value ? updateAgentType : createAgentType)({data: {...formData.value, id: typeId.value }});
    visible.value = false;
    Message.success(typeId.value? '修改' :'新增成功');
    emit('submit')
  }finally{
    loading.value = false;
  }
}
// 取消
const cancel = () => {
  visible.value = false;
  emit('cancel');
};
defineExpose({
  init,
});
</script>

<style lang="scss" scoped>
.type-tab {
  display: flex;
  align-items: center;
  background-color: #eee;
  border-radius: 8px;
  padding: 4px;
  margin-bottom: 20px;
  .tab-item {
    width: 50%;
    color: #999;
    text-align: center;
    border-radius: 8px;
    padding: 2px 0;
    transition: all .2s ease-in;
    &.active {
      color: #333;
      background-color: #fff;
    }
  }
}
</style>
